import Taro, { Component } from '@tarojs/taro';
import { View, Button, Text, ScrollView } from '@tarojs/components';
import UserBox from '../../../components/user-box';
import NavigationBar from '../../../components/navigationBar/index';

import './index.scss';
import { userLowerAgent } from '../../../services/user';

class Agency extends Component {
  config = {
    navigationBarTitleText: '我的代理商',
  };

  state =  {
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    userInfo: Taro.getStorageSync('userInfo'),
    agencyList: [],
    isMore: false,
    pageData: {
      page: 1,
      page_number: 10,
    },
  }


  componentWillUnmount() {}

  componentDidShow() {}

  componentDidHide() {}

  componentWillMount() {
    let temp = this.state.pageData
    userLowerAgent({
      id: this.state.userInfo.id,
      ...temp,
    }).then(res => {
      temp.page++
      this.setState({
        agencyList: res.list,
        isMore: res.list.length < res.total,
        pageData: temp,
      })
    })
  }

  onScrollToLower() {
    if (this.state.isMore) {
      let temp = this.state.pageData
      let tempList = this.state.agencyList
      userLowerAgent({
        id: this.state.userInfo.id,
        ...temp,
      }).then(res => {
        tempList = tempList.concat(res.list)
        temp.page++
        this.setState({
          agencyList: tempList,
          isMore: tempList.length < res.total,
          pageData: temp,
        })
      })
    }
  }

  calcLevel(level) {
    switch(level) {
      case 3: return '普通用户';
      case 2: return '区域代理';
      case 1: return '省级代理';
    }
  }

  render() {
    let { agencyList } = this.state;
    return (
      <View className='agency' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text="我的代理商" />
        <ScrollView
          className='agency-list'
          scrollY
          scrollWithAnimation
          onScrollToLower={this.onScrollToLower}
        >
          {
            agencyList.map(agency => {
              if (agency) return <UserBox key={agency.id} agencyId={agency.id} nickname={agency.nickname} avatar={agency.avatar} level={this.calcLevel(agency.level)} />
            })
          }
        </ScrollView>
      </View>
    );
  }
}

export default Agency;
